import './header.js'
import { order_list_api, order_update_api } from './../api/order.js'
import { ajax_upload_api, user_profile_api } from './../api/user_api.js'
import { baseURL } from './../utils/http.js'

let account = [
    {
        id: 1,
        username: "xiaowang",
        pwd: 123456,
    },
]
let infoObj = {}//基本信息
let flag1 = false
let flag2 = false
let flag3 = false
let fla1 = false
let fla2 = false

let orders = []
const order_filter_arr = ['入住中','预定中','完成', '取消']
let filterState = '入住中'
const user_info_form = {
    avatar: '',
    username: ''
}

let state = -1
let oorderWrapper = document.querySelector(".orderWrapper")
let otbody3tr1 = document.querySelector(".tbody3 tr:nth-child(1)")
let otbody3tr2 = document.querySelector(".tbody3 tr:nth-child(2)")
let otbody3tr3 = document.querySelector(".tbody3 tr:nth-child(3)")
let otbody3tr4 = document.querySelector(".tbody3 tr:nth-child(4)")
let ooldPwdInp = otbody3tr1.querySelector("input")
let onewPwdInp = otbody3tr2.querySelector("input")
let osurePwdInp = otbody3tr3.querySelector("input")
let ooldPwdTips1 = otbody3tr1.querySelector("span:nth-of-type(1)")
let ooldPwdTips2 = otbody3tr1.querySelector("span:nth-of-type(2)")
let onewPwdTips = otbody3tr2.querySelector("span")
let osurePwdTips1 = otbody3tr3.querySelector("span:nth-of-type(1)")
let osurePwdTips2 = otbody3tr3.querySelector("span:nth-of-type(2)")

let oPwdSaveBtn = otbody3tr4.querySelector("button")
let otbody2tr1 = document.querySelector(".tbody2 tr:nth-child(1)")
let otbody2tr2 = document.querySelector(".tbody2 tr:nth-child(2)")
let otbody2tr3 = document.querySelector(".tbody2 tr:nth-child(3)")
let otbody2tr4 = document.querySelector(".tbody2 tr:nth-child(4)")
let otbody2tr5 = document.querySelector(".tbody2 tr:nth-child(5)")
let otbody2tr6 = document.querySelector(".tbody2 tr:nth-child(6)")
let otbody2tr7 = document.querySelector(".tbody2 tr:nth-child(7)")

let onicknameInp = otbody2tr1.querySelector("input")
let ogenderInps = otbody2tr2.querySelectorAll("td:nth-child(2) input")
// let oyearSelect = otbody2tr3.querySelector("td:nth-child(2) select:nth-child(1)")
// let omonthSelect = otbody2tr3.querySelector("td:nth-child(2) select:nth-child(2)")
// let odaySelect = otbody2tr3.querySelector("td:nth-child(2) select:nth-child(3)")
// let olifeInps = otbody2tr4.querySelectorAll("td:nth-child(2) input")
// let ofieldSelect = otbody2tr5.querySelector("td:nth-child(2) select:nth-child(1)")
// let opositionSelect = otbody2tr5.querySelector("td:nth-child(2) select:nth-child(2)")
// let osignatureInp = otbody2tr6.querySelector("input")
let onicknameTips = otbody2tr1.querySelector("span")
// let osignatureTips = otbody2tr6.querySelector("span")
// let otbody2SaveBtn = otbody2tr7.querySelector("button")
main()
function main() {
    get_order_list_req()
    pwdModify()
    control_order_filter_event()
    render_order_filter()
    init_user_info()
    file_upload_event()
    username_input_event()
    submit_user_info_event()
}
//请求订单数据
function get_order_list_req(params) {
    order_list_api({ status: filterState }).then(res => {
        orders = res.data
        renderMyOrder()
    })
}
function renderMyOrder() {
    let template = ``
    for (let index = 0; index < orders.length; index++) {
        const element = orders[index];
        template += `
    <div class="order">
        <div class="orderTop">
            <div class="orderTopLeft">
                <span>${transform_date(element.createtime*1000)}</span>
            </div>
            <img clickIndex="${index}" src="" alt="">         
        </div>
        <div class="orderBottom">
            <div class="orderDetail">
                <div class="orderDetailLeft">
                    <div><img src="${baseURL + element.room.image}" alt=""></div>
                    <div class="text">
                        <h4 class="filmTitle">${element.room.name}</h4>
                        <p class="cinema">${element.room.type_text}</p>
                        <p class="date">入住日期：${element.start_time}</p>
                        <p class="date">退房日期：${element.end_time}</p>
                    </div>
                </div>
                <div class="orderDetailRight">
                    <span>￥${element.total}</span>
                    <span>${element.status_text}</span>
                    <div class="btn">
                    <button data-id="${element.id}" data-status=${element.status} class="check_order_detail_btn ${element.status=='入住中'||element.status=='预定中'?'':'check_order_detail_none'}">
                        ${element.status=='入住中'?'退房':element.status=='预定中'?'取消':''}
                    </button>
                    </div>
                </div>
            </div>
        </div>
    </div>`
    }
    oorderWrapper.innerHTML = template
    // delOrder()
    changePage()
    cancel_order_event()
}
function splitSeats(seatArray) {
    let template1 = ``
    for (let index1 = 0; index1 < seatArray.length; index1++) {
        const element1 = seatArray[index1];
        let newSplitArray = element1.split("-")
        template1 += newSplitArray[0] + `排` + newSplitArray[1] + `号&nbsp;`
    }
    return (template1)
}
function delOrder() {
    let odel = document.querySelector(".orderTop img")
    odel.onclick = function () {
        let oclickIndex = odel.getAttribute("clickIndex")
        for (let index2 = 0; index2 < orders.length; index2++) {
            const element2 = orders[index2];
            if (oclickIndex == index2) {
                orders.splice(index2, 1)
                break
            }
        }
        renderMyOrder()
    }
}
function changePage() {
    let oul = document.querySelector(".mainLeft ul")
    let olis = oul.querySelectorAll("li")
    let omainRights = document.querySelectorAll(".main>div")
    for (let index3 = 0; index3 < olis.length; index3++) {
        const element3 = olis[index3];
        element3.onclick = function () {
            for (let index4 = 0; index4 < olis.length; index4++) {
                const element4 = olis[index4];
                element4.removeAttribute("class")
            }
            element3.className = "active"
            //为什么循环绑定事件的过程都已经结束了，还能在事件触发时拿到循环绑定时的循环变量

            state = index3
            for (let index5 = 0; index5 < omainRights.length; index5++) {
                const element5 = omainRights[index5];
                if (index5 == state) {
                    for (let index6 = 0; index6 < omainRights.length; index6++) {
                        const element6 = omainRights[index6];
                        element6.setAttribute("style", "display: none;")
                    }
                    element5.setAttribute("style", "display: block;")
                }
            }
            changePage()
        }
    }
}
function pwdModify() {
    ooldPwdInp.onblur = oldPwdInpVerify
    onewPwdInp.onblur = newPwdInpVerify
    osurePwdInp.onblur = surePwdInpVerify
    oPwdSaveBtn.onclick = function () {
        if (oldPwdInpVerify() && newPwdInpVerify() && surePwdInpVerify()) {
            alert("密码保存成功")
        }
    }
}
function oldPwdInpVerify() {
    if (ooldPwdInp.value == "") {
        ooldPwdTips1.setAttribute("style", "display:inline;")
    }
    else {
        ooldPwdTips1.setAttribute("style", "display:none;")
        if (ooldPwdInp.value != account[0].pwd) {
            ooldPwdTips2.setAttribute("style", "display:inline;")
        } else {
            ooldPwdTips2.setAttribute("style", "display:none;")
            flag1 = true
        }
    }
    return flag1
}
function newPwdInpVerify() {
    if (onewPwdInp.value == "") {
        onewPwdTips.setAttribute("style", "display:inline;")
    } else {
        onewPwdTips.setAttribute("style", "display:none;")
        flag2 = true
    }
    return flag2
}
function surePwdInpVerify() {
    if (osurePwdInp.value == "") {
        osurePwdTips1.setAttribute("style", "display:inline;")
    } else {
        osurePwdTips1.setAttribute("style", "display:none;")
        if (osurePwdInp.value != onewPwdInp.value) {
            osurePwdTips2.setAttribute("style", "display:inline;")
        } else {
            osurePwdTips2.setAttribute("style", "display:none;")
            flag3 = true
        }
    }
    return flag3
}
function infoModify() {
    onicknameInp.onblur = nicknameInpVerify
    osignatureInp.onblur = signatureInpVerify
    otbody2SaveBtn.onclick = function () {
        if (nicknameInpVerify() && signatureInpVerify()) {
            alert("保存成功")
            infoObj.name = onicknameInp.value
            for (let index = 0; index < ogenderInps.length; index++) {
                const element = ogenderInps[index];
                if (element.checked) {
                    infoObj.gender = element.value
                }
            }
            let tempdate = `` + oyearSelect.value + "/" + omonthSelect.value + "/" + odaySelect.value
            infoObj.date = tempdate
            for (let index1 = 0; index1 < olifeInps.length; index1++) {
                const element1 = olifeInps[index1];
                if (element1.checked) {
                    infoObj.life = element1.value
                }
            }
            let tempWork = `` + ofieldSelect.value + `-` + opositionSelect.value
            infoObj.work = tempWork
            infoObj.signature = osignatureInp.value
            console.log(infoObj);
        }
    }

}
function nicknameInpVerify() {
    if (onicknameInp.value == "") {
        onicknameTips.setAttribute("style", "display:inline;")
    } else {
        onicknameTips.setAttribute("style", "display:none;")
        fla1 = true
    }
    return fla1
}
function signatureInpVerify() {
    if (osignatureInp.value == "") {
        osignatureTips.setAttribute("style", "display:inline;")
    } else {
        osignatureTips.setAttribute("style", "display:none;")
        fla2 = true
    }
    return fla2
}
//渲染订单筛选器
function render_order_filter(params) {
    let tempdate = ''
    order_filter_arr.forEach((item, index) => {
        tempdate += `
        <div filterState="${item}" class="filter_item ${filterState == item ? 'order_filter_active' : ''}">${item}</div>`
    })
    $('.order_filter').html(tempdate)
}
//控制订单筛选器切换
function control_order_filter_event(params) {
    $('.order_filter').on('click', '.filter_item', function () {
        filterState = $(this).attr('filterState')
        render_order_filter()
        get_order_list_req()
    })
}
//取消订单
function cancel_order_event(params) {
    $('.check_order_detail_btn').on('click', function () {
        let id =  $(this).data('id')
        let curStatus=$(this).attr('data-status')
        let changeStatus=''
        if (curStatus=='入住中') {
            changeStatus=='完成'
        }else if (curStatus=='预定中') {
            changeStatus=='取消'
        }
        order_update_api({id:id, status: changeStatus}).then(res => {
            alert('操作成功')
            get_order_list_req()
        }).catch(err => {
            alert('操作失败')
        })
    })
}
//转换date为本地时间字符串
function transform_date(date) {
    return new Date(date).toISOString().split('T')[0]
}
//用户信息初始化
function init_user_info(params) {
    const user_info = JSON.parse(localStorage.getItem('userInfo'))
    Object.keys(user_info_form).forEach(keyItem => {
        user_info_form[keyItem] = user_info[keyItem]
    })
    //localStorage中的avatar返的是base64
    $('.info-left div img').attr('src', user_info_form.avatar)
    $('.username_input').attr('value', user_info_form.username)
}
//绑定文件上传更改事件
function file_upload_event(params) {
    $("#fileInput").on("change", function () {
        var file = this.files[0];
        if (file) {
            $("#fileInput").attr('disabled', true)
            const form_data = new FormData()
            form_data.append('file', file)
            $.ajax({
                url: baseURL + '/index/ajax/upload', // 服务器端处理文件上传的脚本地址
                type: 'POST',
                data: form_data,
                processData: false, // 告诉jQuery不要处理发送的数据
                contentType: false, // 告诉jQuery不要设置Content-Type请求头
                headers:{
                    token:localStorage.token
                },
                success: function (res) {
                    $("#fileInput").attr('disabled', false)
                    $('.info-left div img').attr('src', baseURL + res.data.url)
                    user_info_form.avatar=res.data.url
                }
            });
        } else {
            alert('未成功选取文件')
        }
    });
}
//用户名输入框change事件
function username_input_event(params) {
    $('.username_input').on('change', function () {
        user_info_form.username = $(this).val()
    })
}
//保存提交用户信息事件
function submit_user_info_event(params) {
    $('.userInfo_save_btn').on('click', function () {
        if (user_info_form.username) {
            user_profile_api(user_info_form).then(res => {
                const user_info = JSON.parse(localStorage.getItem('userInfo'))
                user_info.username=user_info_form.username
                user_info.avatar=user_info_form.avatar
                localStorage.setItem('userInfo',JSON.stringify(user_info))
                location.reload()
            }).catch(err => {
                alert('保存失败')
            })
        } else {
            alert('用户名不能为空')
        }
    })
}